package com.boot.filter;

import com.boot.token.MyToken;
import com.boot.utils.JwtUtils;
import org.apache.shiro.web.filter.AccessControlFilter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class StatelessAuthcFilter extends AccessControlFilter {
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception {
        return false;
    }
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        try {
            //1、获取token值
            String token = request.getParameter("token");
            //2、通过token值获取用户名:如果获取不到用户名 说明token不正确 或者做token校验
            String userName = JwtUtils.getUserName(token);

            //3、从数据库中查询账号密码
            String password = "123456";

            //4、生成无状态Token
            MyToken myToken = new MyToken(userName, password, token);
            //5、委托给Realm进行登录
            getSubject(request, response).logout();
        } catch (Exception e) {
            e.printStackTrace();
            onLoginFail(response); //6、登录失败
            return false;
        }
        return true;
    }

    //登录失败时默认返回401状态码
    private void onLoginFail(ServletResponse response) throws IOException {
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        //httpResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        httpResponse.getWriter().write("login error");
    }
}
